# -*- coding: utf-8 -*-
import threading
import os
from PyQt5.QtCore import QThread, pyqtSignal,QSettings
from socket import *
from cmomon import FuncReduceHttpRequest
setting = QSettings(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"config\\config.ini"), QSettings.IniFormat)
setting.setIniCodec("UTF-8")

class Server_RunThread(QThread):
    tcp_action_signal = pyqtSignal(str)
    def __init__(self):

        super().__init__()
        self.HOST = setting.value("tcp_config/HTTP_IP_HOST")
        self.POST = setting.value("tcp_config/HTTP_IP_PORT")
        self.add = (self.HOST, int(self.POST))
        # 创建一个tcp套接字
        self.listen_socket = socket(AF_INET, SOCK_STREAM)
        # 允许立即使用上次绑定的port
        self.listen_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        # 绑定
        self.listen_socket.bind(self.add)
        # 变为被动，并制定队列的长度
        self.listen_socket.listen(128)

    def run(self):
        try:
            while True:
                # 等待新客户端到来
                client_socket, client_address = self.listen_socket.accept()
                new_process = threading.Thread(target=self.handleRequest, args=(client_socket,))
                new_process.start()
                # 因为线程是共享同一个套接字，所以主线程不能关闭，否则子线程就不能再使用这个套接字了
                # client_socket.close()
        except:
            print("shibai")

    def handleRequest(self, client_socket):
        '''
        :param client_socket:
        :return:
        '''
        try:
            recv_date = client_socket.recv(1024).decode("utf-8")
            if len(recv_date) > 0:
                # 得到的数据
                ret = FuncReduceHttpRequest(recv_date)
                self.tcp_action_signal.emit(str(ret))
                response_start_line = "HTTP/1.1 200 OK\r\n"
                response_headers = "Server: My server\r\n"
                response_body = "success"
                response = response_start_line + response_headers + "\r\n" + response_body
                client_socket.send(response.encode("utf-8"))
            else:
                response_start_line = "HTTP/1.1 403 OK\r\n"
                response_headers = "Server: My server\r\n"
                response_body = "faled"
                response = response_start_line + response_headers + "\r\n" + response_body
                client_socket.send(response.encode("utf-8"))
                pass
            client_socket.close()
        except Exception as f:
            print(f)


